<?php
namespace app\api\logic;

use app\common\logic\BaseLogic;
use app\common\service\ConfigService;
use app\common\service\FileService;
use app\common\model\diy\DiyFormFieldData;
use app\common\model\diy\DiyFormFieldType;
use think\facade\Cache;


/**
 * 配置逻辑层
 * Class ConfigLogic
 * @package app\api\logic
 */
class ConfigLogic extends BaseLogic
{

    /**
     * @notes 获取政策协议
     * @param string $type
     * @return array
     */
    public static function getPolicyByType(string $type)
    {
        // 获取缓存
        $content = ConfigService::get('agreement', $type . '_content', '');

        // 处理协议变量
        $content = str_replace('[当前时间]',date('Y年m月d日'),$content);
        $userInfo = request()->userInfo;
        if (isset($userInfo['user_id']) && $userInfo['user_id']>0){
            $content = str_replace('[用户ID]',$userInfo['user_id'],$content);
            $content = str_replace('[用户姓名]',$userInfo['real_name'],$content);
        }else{
            $content = str_replace('[用户ID]','',$content);
            $content = str_replace('[用户姓名]','',$content);
        }
        return [
            'title' => ConfigService::get('agreement', $type . '_title', ''),
            'content' => $content,
        ];
    }


    /**
     * @notes 获取配置
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigData()
    {
        // 获取缓存
        $app_ad_slide = ConfigService::get('website', 'app_ad_slide','');
        $app_service_image = ConfigService::get('website', 'app_service_image','');
        $apiConfigData = [
            'app_config'=>[
                'app_name' => ConfigService::get('website', 'app_name',''),
                'app_down_url' => ConfigService::get('website', 'app_down_url',''),
                'app_ios_down_url' => ConfigService::get('website', 'app_ios_down_url',''),
                'app_service_url' => ConfigService::get('website', 'app_service_url',''),
                'app_logo' => FileService::getFileUrl(ConfigService::get('website', 'app_logo','')),
                'app_service_image' => $app_service_image ? FileService::getFileUrl($app_service_image) : '',
                'app_ad_slide' => $app_ad_slide ? FileService::getFileUrl($app_ad_slide) : '',
                'app_ad_slide_url' => ConfigService::get('website', 'app_ad_slide_url',''),
            ],
        ];
        return $apiConfigData;
    }

    /**
     * 获取动态表单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTreeFormList()
    {
        // 后续设置缓存 // 数据变动再去除
        $list = DiyFormFieldType::where('status',1)
            ->field('id,name,other_name,field_key')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
        foreach ($list as &$item){
            $item['check'] = false;
            $options = DiyFormFieldData::where([
                ['type_id','=',$item['id']],
                ['status','=',1]
            ])
            ->field('id,name,value,type_id,estimate_amount')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->select()
            ->toArray();
            if ($options){
                $item['options'] = $options;
            }else{
                unset($item);
            }
            unset($options);
        }
        return $list;
    }


    /**
     * 获取当前定位
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLocation()
    {
        $config = ConfigService::get('jumei_location');
        try{
            $response = (new \GuzzleHttp\Client)->request('POST', $config['jumeiApi']."/ip/address-query", [
                'headers'=>[
                    'Authorization'=>"APPCODE " . $config['jumeiAppCode'],
                    'Content-Type'=>"application/x-www-form-urlencoded; charset=UTF-8",
                ],
                'form_params'=>[
                    'ip'=>\request()->getLocalIp()
                ]
            ]);
            $content = $response->getBody()->getContents();
            $res = json_decode($content,true);
            if($res['code'] == 200){
                return ['code'=>200,'data'=>$res['data']];
            }
            return ['code'=>400];
        }catch (\Exception $e){
            return ['code'=>400];
        }
    }
}